<template lang="">
  <div class="_wrapper">
    <div class="_wrapper" style="height: 105%" id="com-map-baidu-id"></div>
  </div>
</template>
<script>
import toolLoadJs from "@/tool/tool-load-js.js";
import toolWaitObj from "@/tool/tool-wait-obj";
import RainSymbolInit from "./RainSymbol.js";
import ToolMapBaiduInit from "./ToolMapBaidu";
import ToolMapVglInit from "./ToolMapVgl";
import ComplexCustomOverlaysInit from "./ComplexCustomOverlay.js";

// 地图原始对象
let map;
// 地图vgl原始对象
let mapVgl;
// 下雨组件
let RainSymbol;
// 地图工具类
let ToolMapBaidu;

// 当前区域名称
let proname = "山东省";
// 当前区域升读
let prokind = 1;
// 当前区域对象
let dist = null;

export default {
  props: {
    isMapVgl: {
      type: Boolean,
      default: false,
    },
    isAnimation: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
    this.init();
    setTimeout(() => {
      // this.addMarker(
      //   { x: 113.676547, y: 34.774079, id: "xxxxx" },
      //   {
      //     w: 45,
      //     h: 45,
      //     x: 20,
      //     y: 25,
      //     icon: "http://115.29.192.252:39000/public/logo.png",
      //     type: "rain",
      //     size: 100,
      //   }
      // );
      // this.addMarker3D(
      //   { x: 113.576547, y: 34.674079, id: "xxxxx" },
      //   {
      //     w: 45,
      //     h: 45,
      //     x: 20,
      //     y: 25,
      //     icon: "http://115.29.192.252:39000/public/logo.png",
      //   }
      // );
      // this.addPolyline(
      //   [
      //     [113.676547, 34.774079],
      //     [114.676547, 35.774079],
      //     [115.676547, 36.774079],
      //     [116.676547, 37.774079],
      //   ],
      //   {
      //     strokeColor: "red",
      //     strokeWeight: 3,
      //     strokeOpacity: 0.8,
      //   }
      // );
      // this.addPolygon(
      //   [
      //     [116.676547, 35.774079],
      //     [117.676547, 32.774079],
      //     [118.676547, 39.774079],
      //     [119.676547, 40.774079],
      //   ],
      //   {
      //     strokeColor: "red",
      //     strokeWeight: 3,
      //     strokeOpacity: 0.8,
      //   }
      // );
      // this.addPolygonEmpty([
      //   [113.686147, 34.774079],
      //   [113.696147, 34.774079],
      //   [113.696147, 34.794079],
      //   [113.686147, 34.794079],
      // ]);
      // this.addPrism([
      //   [113.787147, 34.875079],
      //   [113.797147, 34.875079],
      //   [113.797147, 34.895079],
      //   [113.787147, 34.895079],
      // ]);
      // this.addLabel({ x: 113.687147, y: 34.888079 }, "内容测试");
      // this.addBezierCurve(
      //   [
      //     [116.399, 39.91],
      //     [113.399, 39.91],
      //     [110.399, 39.91],
      //   ],
      //   [
      //     [
      //       [115.399, 40.91],
      //       [114.399, 38.91],
      //     ],
      //     [[112.399, 38.91]],
      //   ]
      // );
      // mapVgl.addLineRainbowLayer([
      //   [113.586147, 34.774079],
      //   [113.596147, 34.774079],
      //   [113.596147, 34.794079],
      //   [113.586147, 34.794079],
      // ]);
      // map.addOverlay(
      //   new (ComplexCustomOverlaysInit())(
      //     [113.787147, 34.888079],
      //     "银湖海岸城",
      //     "测试内容"
      //   )
      // );
      // this.addCustomerDom([113.787147, 34.988079], () => {
      //   let div = document.createElement("div");
      //   div.style.backgroundColor = "#fff";
      //   div.style.height = "50px";
      //   div.style.width = "50px";
      //   div.appendChild(document.createTextNode("测试内容"));
      //   return div;
      // });
      // this.addGroundOverlay(
      //   [
      //     [114.186147, 35.174079],
      //     [113.996147, 34.975079],
      //   ],
      //   "http://115.29.192.252:39000/manager-project/brk2ldkhuyalq4qoaoh4.jpg"
      // );
      // this.initDistrict("河南省", 1);
    }, 3000);
  },
  methods: {
    clear() {
      map.clearOverlays();
    },
    getCurrPosition() {
      return new Promise((ok) => {
        if (
          navigator &&
          navigator.geolocation &&
          navigator.geolocation.requestAuthorization
        ) {
          navigator.geolocation.requestAuthorization(function (status) {
            if (status === "granted") {
              // 用户已授权，可以进行定位操作
              navigator.geolocation.getCurrentPosition(
                function (position) {
                  var lat = position.coords.latitude; // 纬度
                  var lng = position.coords.longitude; // 经度
                  var point = new BMap.Point(lng, lat); // 创建坐标点
                  this.addMarker({ x: lng, y: lat });
                  map.panTo(point); // 将地图中心点移动到当前位置
                },
                function (error) {
                  alert("获取位置信息失败：" + error.message);
                }
              );
            } else {
              // 用户拒绝了授权，无法进行定位操作
              alert("用户拒绝授权...");
            }
          });
        } else {
          let geolocation = new BMapGL.Geolocation();
          geolocation.getCurrentPosition((r) => {
            this.clear();
            this.addMarker({ x: r.point.lng, y: r.point.lat });
            map.panTo(r.point);
            ok(r.point);
          });
        }
      });
    },
    /**
     * 基于 geojson 生成overlay
     */
    generatorOverlayByGeoJson(geoJson, callback = () => {}) {
      var gParse = new BMapGL.GeoJSONParse({
        reference: "GCJ02",
      });

      gParse.readFeaturesFromObject(
        geoJson,
        { fillColor: "red" },
        function (overlay) {
          callback(overlay);
        }
      );
    },
    /**
     * 开启点聚合
     */
    openMarkerClusterer() {
      var markerClusterer = new BMapLib.MarkerClusterer(map, {
        markers: markers,
      });
    },
    addOverlays() {
      if (fs.length > 0) {
        return;
      }
      fs = gParse.readFeaturesFromObject(
        region1,
        {
          fillColor: "red",
        },
        function (overlay) {
          var index = overlay.properties.join || 0;
          overlay.setFillColor(colorBand[index]);
          overlay.setZIndex(-2);
          overlay.addEventListener("onclick", popup);
          map.addOverlay(overlay);
        }
      );
      bj = gParse.readFeaturesFromObject(
        beijing1,
        {
          strokeColor: "darkred",
          strokeWeight: 4,
          fillOpacity: 0.6,
        },
        function (overlay) {
          overlay.setZIndex(-1);
          map.addOverlay(overlay);
        }
      );
    },
    /**
     * 行政区域操作
     * proname 区域名称
     * prokind 区域层级 - 0：省，1：市，2：区
     * todo 遗留问题
     * 1. 不能显示全国
     * 2. 点击事件拿不到区域信息
     */
    initDistrict(proname, prokind = 1) {
      map.removeDistrictLayer(dist);
      // --- 添加行政区划 ---
      dist = new BMapGL.DistrictLayer({
        name: `(${proname})`,
        kind: prokind,
        fillColor: "#618bf8",
        fillOpacity: 0.8,
        strokeColor: "#daeafa",
        viewport: true,
      });
      map.addDistrictLayer(dist);

      // --- 行政区划添加鼠标事件 ---
      dist.addEventListener("mouseover", function (e) {
        e.currentTarget.setFillColor("#9169db");
      });
      dist.addEventListener("mouseout", function (e) {
        e.currentTarget.setFillColor(e.currentTarget.style.fillColor);
      });
      dist.addEventListener("click", function (e) {
        console.log(e);
      });
    },
    /**
     * 添加贴图 - 图片
     * type - image 图片
     * type - canvas canvas
     * type - video 视频
     */
    addGroundOverlay(points, url, opacity = 1, type = "image") {
      var pStart = new BMapGL.Point(points[0][0], points[1][1]);
      var pEnd = new BMapGL.Point(points[1][0], points[0][1]);
      var bounds = new BMapGL.Bounds(
        new BMapGL.Point(pStart.lng, pEnd.lat),
        new BMapGL.Point(pEnd.lng, pStart.lat)
      );
      let imgOverlay = new BMapGL.GroundOverlay(bounds, {
        type: type,
        url: url,
        opacity: opacity,
      });
      map.addOverlay(imgOverlay);
    },
    addCustomerDom(points, domFun, option) {
      // 创建自定义覆盖物
      var customOverlay = new BMapGL.CustomOverlay(
        function () {
          let dom = domFun();
          dom.style.zIndex = BMapGL.Overlay.getZIndex(this.point.lat);
          return dom;
        },
        {
          point: new BMapGL.Point(points[0], points[1]),
          opacity: 0.5,
          offsetY: 100,
          ...option,
        }
      );
      map.addOverlay(customOverlay);
    },
    /**
     * 添加3D棱柱
     * points 坐标组
     * height 高度
     * option.topFillColor 顶面填充颜色
     * option.topFillOpacity 顶面填充透明度
     * option.sideFillColor 侧面填充颜色
     * option.sideFillOpacity 侧面填充透明度
     */
    addPrism(points, height = 500, option) {
      var prism = new BMapGL.Prism(this.transformMapPos(points), height, {
        topFillColor: "#5679ea",
        topFillOpacity: 0.5,
        sideFillColor: "#5679ea",
        sideFillOpacity: 0.9,
        ...option,
      });
      map.addOverlay(prism);
    },
    /**
     * 添加贝塞尔曲线
     * @param {Array} paths 路径点列表
     * @param {Object} points 贝塞尔点列表
     */
    addBezierCurve(paths, points) {
      let bc = new BMapGL.BezierCurve(
        paths.map((path) => new BMapGL.Point(path[0], path[1])),
        points.map((pointArr) => {
          return pointArr.map((point) => new BMapGL.Point(point[0], point[1]));
        })
      );
      map.addOverlay(bc);
    },
    // 添加标签
    addLabel(pointOpt, content) {
      var opts = {
        position: new BMapGL.Point(pointOpt.x, pointOpt.y), // 指定文本标注所在的地理位置
        offset: new BMapGL.Size(0, 0), // 设置文本偏移量
      };
      // 创建文本标注对象
      var label = new BMapGL.Label(content, opts);
      // 自定义文本标注样式
      label.setStyle({
        color: "blue",
        borderRadius: "5px",
        borderColor: "#ccc",
        padding: "5px",
        fontSize: "16px",
        // height: "30px",
        lineHeight: "20px",
        fontFamily: "微软雅黑",
      });
      map.addOverlay(label);
    },
    /**
     * 添加信息窗口
     * contetn 内容
     * opts.width 宽度
     * opts.height 高度
     * opts.title 标题
     * pointArr 坐标
     */
    addInfoWin(content, opts, pointArr) {
      let infoWindow = new BMapGL.InfoWindow(content, opts);
      map.openInfoWindow(
        infoWindow,
        new BMapGL.Point(pointArr[0], pointArr[1])
      );
    },
    /**
     * 设置poi样式
     * option.poiText poi的文本
     * option.poiIcon poi的图标
     * option.overlay 覆盖物
     * option.layer 叠加图层
     * option.building 3D建筑物
     * option.street 路网 - 地球模式及卫星地图有效
     */
    disConfig(option) {
      map.setDisplayOptions(option);
    },
    /**
     * 地图中心点坐标
     */
    mapCenter(pointArr) {
      if (pointArr && pointArr.length == 2) {
        map.setCenter(new BMapGL.Point(pointArr[0], pointArr[1]));
      }
      let cen = map.getCenter();
      return [cen.lng.toFixed(5), cen.lat.toFixed(5)];
    },
    /**
     * 添加镂空面
     */
    addPolygonEmpty(positions = []) {
      this.addPolygon(positions, {
        fillColor: "blue",
        fillOpacity: 0.2,
      });
    },
    /**
     * 添加多边形
     * option.strokeColor 颜色
     * option.strokeWeight 线宽
     * option.strokeOpacity 透明度
     */
    addPolygon(positions = [], option = {}) {
      let polyline = new BMapGL.Polygon(
        this.transformMapPos(positions),
        option
      );
      map.addOverlay(polyline);
    },
    /**
     * 添加线
     * option.strokeColor 颜色
     * option.strokeWeight 线宽
     * option.strokeOpacity 透明度
     */
    addPolyline(positions = [], option = {}) {
      let polyline = new BMapGL.Polyline(
        this.transformMapPos(positions),
        option
      );
      map.addOverlay(polyline);
    },
    transformMapPos(positions = []) {
      let posArray = [];
      positions.forEach((element) => {
        posArray.push(new BMapGL.Point(element[0], element[1]));
      });
      return posArray;
    },
    /**
     * todo 异常
     */
    addMarker3D(pointOpt, icon, enableDragging = false) {
      let point = new BMapGL.Point(pointOpt.x, pointOpt.y);
      let marker = new BMapGL.Marker3D(point, 5000, {
        size: 50,
        icon: ToolMapBaidu.buildIcon(icon),
        // shape: "BMAP_SHAPE_CIRCLE",
        // fillColor: "#454399",
        // fillOpacity: 0.6,
      });
      map.addOverlay(marker);
    },
    /**
     * 添加点
     * pointOpt.x 为点的x坐标
     * pointOpt.y 为点的y坐标
     * pointOpt.click 点击事件
     * icon.w 宽度
     * icon.h 高度
     * icon.x x偏移量
     * icon.y y偏移量
     * icon.imgX 图片偏移量
     * icon.imgY 图片偏移量
     * icon.icon 图标路径
     * enableDragging 是否可拖拽
     */
    addMarker(pointOpt, icon, enableDragging = false) {
      if (pointOpt.x && pointOpt.y) {
        let point = new BMapGL.Point(pointOpt.x, pointOpt.y);

        let marker = new BMapGL.Marker(point, {
          // 点位拖拽
          enableDragging,
          // 图标
          icon: ToolMapBaidu.buildIcon(icon),
        });

        marker.addEventListener("click", () => {
          if (pointOpt.click) {
            pointOpt.click();
          } else {
            this.addInfoWin(
              "您点击了标注" + pointOpt.id,
              { title: pointOpt.id },
              [pointOpt.x, pointOpt.y]
            );
          }
        });

        map.addOverlay(marker); // 将标注添加到地图中
      }
    },
    /**
     * 返回map原生对象
     */
    map() {
      return map;
    },
    /**
     * 返回mapVgl原生对象
     */
    mapVgl() {
      return mapVgl;
    },
    /**
     * 地图点击事件
     */
    initMapClick() {
      this.map().addEventListener("click", (e) => {
        this.$emit("mapClick", e);
        console.log(e);
      });
    },
    dh(callback) {
      // BMAP_NORMAL_MAP 标准地图
      // BMAP_EARTH_MAP 地球模式
      // BMAP_SATELLITE_MAP 普通卫星模式
      if (!this.isAnimation) {
        callback();
        return;
      }
      map.setMapType(BMAP_EARTH_MAP);
      map.centerAndZoom("郑州市", 5);
      let interval;
      map.addEventListener("tilesloaded", () => {
        if (!interval) {
          interval = setInterval(() => {
            let center = this.mapCenter();
            center[0] = parseFloat(center[0]) - 20;
            this.mapCenter(center);
            if (center[0] < 150 && center[0] > 100) {
              clearInterval(interval);
              callback();
            }
          }, 100);
          // setTimeout(() => {
          //   console.log("清理！");
          //   clearInterval(interval);
          //   callback();
          // }, 5000);
        }
      });
    },
    init() {
      window.comMapCallBack = () => {
        map = new BMapGL.Map("com-map-baidu-id", {
          // 禁止旋转
          // enableRotate: false,
          // 禁止倾斜
          // enableTilt: false,
          // 最小级别
          // minZoom: 5,
          // 最大级别
          // maxZoom: 20,
        });

        this.dh(() => {
          map.centerAndZoom(
            new BMapGL.Point(113.68288767040109, 34.76115964619961),
            13
          );
          // 开启鼠标滚轮缩放
          map.enableScrollWheelZoom(true);

          //设置地图旋转角度
          // map.setHeading(64.5);

          // 地球模式
          // BMAP_NORMAL_MAP 标准地图
          // BMAP_EARTH_MAP 地球模式
          // BMAP_SATELLITE_MAP 普通卫星模式
          map.setMapType(BMAP_NORMAL_MAP);
          //设置地图的倾斜角度
          // map.setTilt(90);
          map.setTilt(45);

          // setTimeout(() => {
          //   // map.centerAndZoom(new BMapGL.Point(115.404, 40.915), 13);
          //   // map.panTo(new BMapGL.Point(113.68288767040109, 34.76115964619961));
          // }, 1000);

          // let scaleCtrl = new BMapGL.ScaleControl(); // 添加比例尺控件
          // map.addControl(scaleCtrl);
          // let zoomCtrl = new BMapGL.ZoomControl(); // 添加缩放控件
          // map.addControl(zoomCtrl);
          // let cityCtrl = new BMapGL.CityListControl(); // 添加城市列表控件
          // map.addControl(cityCtrl);

          // 点线面覆盖物鼠标悬浮提示
          // map.setOverlayMoveCursor(
          //   'url("https://cdn-app.nio.com/PE/2022/2/23/b7d13dfd-b564-4a94-a3ae-7a1e6741daab.svg") 40 53, crosshair'
          // );
          // map.setOverlayMoveCursor("pointer");

          RainSymbol = RainSymbolInit();
          ToolMapBaidu = ToolMapBaiduInit(BMapGL);

          // 初始化mapvgl
          mapVgl = ToolMapVglInit(map);

          // 初始化完成方法
          this.$emit("init-complete", this);

          this.initMapClick();
        });
      };

      toolLoadJs.loadJSList([
        "https://code.bdstatic.com/npm/mapvgl@1.0.0-beta.141/dist/mapvgl.min.js",
        "https://bj.bcebos.com/v1/mapopen/cms/bmapgldemo/custom/mapstyleblack.js",
        "https://bj.bcebos.com/v1/mapopen/api-demos/data/province.js",
        "https://api.map.baidu.com/api?v=1.0&type=webgl&ak=fttGYPhtEERVKvlyqgoag2YgGhrxRQW5&callback=comMapCallBack",
      ]);
    },
  },
};
</script>
<style lang=""></style>
